package com.ziyia.jsontest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void jsonObject(View view) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://test.ziyia.cn/request.php")
                .build();
        new Thread(() -> {
            try {
                Response response = client.newCall(request).execute();
                if (response.body() != null) {
                    String result = response.body().string();
                    Log.d("请求响应", result);
                    parseJsonObject(result);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private void parseJsonObject(String data) {
        try {
            JSONArray jsonArray = new JSONArray(data);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String id = jsonObject.getString("id");
                String name = jsonObject.getString("name");
                String version = jsonObject.getString("version");
                Log.d("解析结果", String.format("%n id = %s，name = %s，version = %s", id, name, version));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void GSONParse(View view) {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url("http://test.ziyia.cn/get_data2.json")
                .build();

        new Thread(() -> {
            try {
                Response response = client.newCall(request).execute();
                ResponseBody body = response.body();
                if (body != null) {
                    parseJSONWithGson(body.string());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

    }


    private void parseJSONWithGson(String jsonData) {
        Type type = new TypeToken<List<Person>>(){}.getType();
        Gson gson = new Gson();
        List<Person> list = gson.fromJson(jsonData, type);
        for (Person person : list) {
            System.out.println("person = " + person);
        }
    }
}